<template>
    <div>
        <el-skeleton :rows="5" animated :loading="loading"/>
        <!-- 查询区域 -->
        <div class="card query-card">
            <el-input
                    v-model="data.userAccount"
                    placeholder="请输入账号"
                    :prefix-icon="Search"
                    class="input-field"
            />
            <el-input
                    v-model="data.userName"
                    placeholder="请输入昵称"
                    :prefix-icon="Search"
                    class="input-field"
            />
            <el-button type="primary" @click="load">查 询</el-button>
        </div>
        <!-- 操作按钮区域 -->
        <div class="card action-card">
            <el-button type="danger">批量删除</el-button>
            <el-button type="primary" @click="toAddPage">新 增</el-button>
            <el-button type="warning" @click="exportData">批量导出</el-button>
            <el-upload
                    action="http://localhost:8080/api/user/import"
                    multiple
                    :show-file-list="false"
                    :on-success="handleImportSuccess"
                    :data="{ token: data.token }"
                    :limit="3"
                    class="upload-button"
            >
                <el-button type="success">批量导入</el-button>
            </el-upload>
        </div>
        <!-- 表格区域 -->
        <div class="card table-card">
            <el-table

                    table-layout="auto"
                    :data="data.userFormList"
                    style="width: 100%"
                    :header-cell-style="{ color: '#333', backgroundColor: '#eaf4ff' }"
                    @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="55"/>
                <el-table-column prop="userName" label="昵称"/>
                <el-table-column prop="userAccount" label="账号"/>
                <el-table-column prop="avatarUrl" label="头像" width="100">
                    <template #default="scope">
                        <el-image
                                v-if="scope.row.avatarUrl"
                                :src="scope.row.avatarUrl"
                                :preview-src-list="[scope.row.avatarUrl]"
                                :preview-teleported="true"
                                lazy
                                class="avatar-image"
                        />
                        <el-image
                                v-else
                                src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
                                title="默认头像"
                                alt="默认头像"
                                class="avatar-image"
                        />
                    </template>
                </el-table-column>
                <el-table-column prop="gender" label="性别">
                    <template #default="scope">
                        {{ scope.row.gender === 1 ? '女' : '男' }}
                    </template>
                </el-table-column>
                <el-table-column prop="phone" label="手机号"/>
                <el-table-column prop="email" label="邮箱"/>
                <el-table-column prop="userRole" label="角色">
                    <template #default="scope">
                        <el-tag type="primary" v-if="scope.row.userRole === 'user'">普通用户</el-tag>
                        <el-tag type="success" v-else>管理员</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="userStatus" label="状态">
                    <template #default="scope">
                        <el-switch
                                v-model="scope.row.userStatus"
                                class="ml-2"
                                inline-prompt
                                :active-value="1"
                                :inactive-value="0"
                                style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
                                active-text="启用"
                                inactive-text="禁用"
                                @change="handleUserStatusChange(scope.row)"
                        />
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <!-- 分页区域 -->
        <div class="card pagination-card">
            <el-pagination
                v-model:current-page="data.currentPage"
                v-model:page-size="data.pageSize"
                layout="prev, pager, next"
                :total="50"
                class="mt-4"
                :size-change="load"
                :current-change="load"
            />
        </div>
        <!-- 新增用户抽屉 -->
        <el-drawer
                title="新增用户"
                v-model="drawerVisible"
                size="30%"
        >
            <div class="demo-drawer__content">
                <el-form
                        :model="form"
                        :rules="rules"
                        label-width="auto"
                        status-icon
                        ref="newUser"
                        class="form-container"
                >
                    <el-form-item label="用户名" prop="userName">
                        <el-input v-model="form.userName"/>
                    </el-form-item>
                    <el-form-item label="账号" prop="userAccount">
                        <el-input v-model="form.userAccount"/>
                    </el-form-item>
                    <el-form-item label="性别">
                        <el-select v-model="form.gender" placeholder="性别">
                            <el-option label="男" value="0"/>
                            <el-option label="女" value="1"/>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="邮箱" prop="email">
                        <el-input v-model="form.email"/>
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model="form.phone"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="onSubmit">Create</el-button>
                        <el-button @click="cancelDrawer">Cancel</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </el-drawer>
    </div>
</template>

<script setup>
import {onMounted, reactive, ref} from "vue";
import {Search} from "@element-plus/icons-vue";
import {useRouter} from "vue-router";
import myAxios from "@/axios/axios.js";
import {ElMessage} from "element-plus";
import {validationRules} from "@/tools/validation.js";

// 加载状态
const loading = ref(true);
// 抽屉可见状态
const drawerVisible = ref(false);
// 路由实例
const router = useRouter();

// 获取本地存储的用户信息
const user = JSON.parse(localStorage.getItem("code_user"));

// 新增用户表单数据
const form = reactive({
    userAccount: "",
    userName: "",
    gender: "",
    email: "",
    phone: "",
});

// 表格数据及分页信息
const data = reactive({
    userName: "",
    userAccount: "",
    pageNum: 1,
    pageSize: 10,
    currentPage: 1,
    total: 100,
    userFormList: [],
    selectedUsers: [],
});

// 表单验证规则
const rules = reactive({
    userAccount: [{validator: validationRules.validateUserAccount, trigger: "change"}],
    userName: [{validator: validationRules.validateUserName, trigger: "change"}],
    email: [{validator: validationRules.validateEmail, trigger: "change"}],
    phone: [{validator: validationRules.validatePhone, trigger: "change"}],
});

// 加载表格数据
const load = async () => {
    try {
        const res = await myAxios.get("/user/list/page/vo", {
            params: {
                userName: data.userName,
                userAccount: data.userAccount,
                pageNum: data.pageNum,
                pageSize: data.pageSize,
            },
        });
        if (res.code === 0 && res.data) {
            data.userFormList = res.data.records;
            data.total = res.data.total;
        } else {
            ElMessage.error("数据加载失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("数据加载出错:", error);
    } finally {
        loading.value = false;
    }
};

// 处理表格选择变化
const handleSelectionChange = (val) => {
    data.selectedUsers = val;
    console.log(val);
};

// 处理用户状态更改
const handleUserStatusChange = async (row) => {
    try {
        const res = await myAxios.post("/user/updateStatus", {
            id: row.id,
            userStatus: row.userStatus,
        });
        if (res.code === 0 || res.data) {
            ElMessage.success("用户状态更新成功");
        } else {
            ElMessage.error("用户状态更新失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("用户状态更新出错:", error);
    }
};

// 处理文件导入成功
const handleImportSuccess = () => {
    ElMessage.success("导入成功");
    load();
};

// 导出数据
const exportData = () => {
    const ids = data.selectedUsers.map((user) => user.id);
    const url = `http://localhost:8080/api/user/exportSelected?userName=${data.userName}&userAccount=${data.userAccount}&ids=${ids}&token=${data.token}`;
    window.open(url);
};

// 打开新增用户抽屉
const toAddPage = () => {
    drawerVisible.value = true;
};

// 提交新增用户表单
const onSubmit = async () => {
    try {
        const res = await myAxios.post("/user/add", form);
        if (res.code === 0 || res.data) {
            ElMessage.success("用户添加成功");
            drawerVisible.value = false;
            load();
        } else {
            ElMessage.error("用户添加失败");
        }
    } catch (error) {
        ElMessage.error("网络请求出错，请稍后重试");
        console.error("用户添加出错:", error);
    }
};

// 关闭新增用户抽屉
const cancelDrawer = () => {
    drawerVisible.value = false;
};

// 组件挂载时加载数据
onMounted(() => {
    load();
});
</script>

<style scoped>
.card {
    padding: 10px;
    background-color: #fff;
    border-radius: 5px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
    margin-bottom: 5px;
}

.query-card {
    display: flex;
    align-items: center;
}

.input-field {
    width: 240px;
    margin-right: 10px;
}

.action-card {
    display: flex;
    align-items: center;
}

.upload-button {
    margin-left: 10px;
}

.table-card {
    /* 可根据需要添加更多样式 */
}

.pagination-card {
    /* 可根据需要添加更多样式 */
}

.demo-drawer__content {
    padding: 20px;
}

.form-container {
    max-width: 400px;
}

.avatar-image {
    border-radius: 50%;
    border: none;
    width: 50px;
    height: 50px;
    z-index: 10000;
}

:deep(.el-table__header th) {
    text-align: center;
}
</style>